package com.example.tourpal;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.DeleteUserMessagesLishenter;
import com.example.tourpal.model.LocalDataLoader.InsertUserMessageLishenter;
import com.example.tourpal.model.LocalDataLoader.MessageRequestLishenter;
import com.example.tourpal.model.LocalDataLoaderHelp;
import com.example.tourpal.model.Page;
import com.example.tourpal.model.PrivateMessage;
import com.example.tourpal.util.ClockAdapter;
import com.example.tourpal.util.MessageIconDrawable;
import com.example.tourpal.util.SharePreferencesManager;
import com.example.tourpal.widget.DynamicListView;
import com.example.tourpal.widget.DynamicListView.DynamicListViewListener;

public class MyMessageActivity extends Activity implements
		DynamicListViewListener {

	private Context context;

	private ImageView back;
	private ImageView refresh;
	private ImageView msgSwitch;
	private TextView privateMsg;
	private TextView systemMsg;
	private ViewPager viewPager;
	private TextView noMessage;
	List<View> views;
	List<MessageAdapter> adapters;
	private int currentPage = 0;
	private int currentTab = 0;
	private int currentMessageDetail = 0;
	private SharePreferencesManager mSharePreferencesManager;
	private List<PrivateMessage> privateMessage = new ArrayList<PrivateMessage>();
	private List<PrivateMessage> systemMessage = new ArrayList<PrivateMessage>();
	private LocalDataLoader mLocalDataLoader = null;

	private int screenWidth = 0;
	private ListView timetagListView;
	private RelativeLayout detail_layout;
	private View send_msg_bottom_layout;
	private LinearLayout viewpage_layout;
	private EditText message_edit;
	private ImageButton message_send_btn;
	private ClockAdapter clockAdapter;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			DynamicListView dynamicListView = (DynamicListView) (views
					.get(currentTab));
			switch (msg.what) {
			case 0:
				dynamicListView.doneRefresh();
				break;
			case 1:
				dynamicListView.doneMore();
				dynamicListView.setSelection((currentPage - 1) * 20);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.me_message_view);
		noMessage = (TextView) findViewById(R.id.noMessage);
		mLocalDataLoader = new LocalDataLoader(this);
		initContentView();
		mSharePreferencesManager = new SharePreferencesManager(this);
		initTotalBarView();
	}

	private void initTotalBarView() {
		back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (detail_layout.getVisibility() == View.VISIBLE) {
					viewpage_layout.animate().translationX(0).setDuration(300);
					detail_layout.animate().translationX(screenWidth)
							.setDuration(300);
					detail_layout.setVisibility(View.GONE);
					send_msg_bottom_layout.animate().translationX(screenWidth)
							.setDuration(300);
					send_msg_bottom_layout.setVisibility(View.GONE);
				} else {
					finish();
				}
			}
		});

		refresh = (ImageView) findViewById(R.id.refresh_img);
		refresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (detail_layout.getVisibility() == View.VISIBLE) {
					showTimerPicker(currentMessageDetail + 1);
				} else {
					initPrivateMessageData(1, 0);
				}
			}
		});

		systemMsg = (TextView) findViewById(R.id.systemMsg);
		systemMsg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				systemMsg.setTextColor(0xff2ba47b);
				privateMsg.setTextColor(0xff888888);
				msgSwitch.setBackgroundResource(R.drawable.msg_r);
				viewPager.setCurrentItem(1);
			}
		});
		privateMsg = (TextView) findViewById(R.id.privateMsg);
		privateMsg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				systemMsg.setTextColor(0xff888888);
				privateMsg.setTextColor(0xff2ba47b);
				msgSwitch.setBackgroundResource(R.drawable.msg_l);
				viewPager.setCurrentItem(0);
			}
		});
		msgSwitch = (ImageView) findViewById(R.id.messageSwitch);
	}

	@Override
	protected void onStart() {
		// mLocalDataLoader.startInsertOneMessageData(21,
		// "hello hello hello hello", null);
		super.onStart();
	}

	@Override
	public boolean onRefreshOrMore(DynamicListView dynamicListView,
			boolean isRefresh) {
		switch (currentTab) {
		case 0:
			if (!isNetworkAvailable()) {
				dynamicListView.doneRefresh();
				dynamicListView.doneMore();
			}

			if (isRefresh) {
				initPrivateMessageData(1, 0);
			} else {
				currentPage++;
				initPrivateMessageData(currentPage, 1);

			}
			break;
		case 1:
			if (!isNetworkAvailable()) {
				dynamicListView.doneRefresh();
				dynamicListView.doneMore();
			}

			if (isRefresh) {
				initSystemMessageData(1, 0);
			} else {
				currentPage++;
				initSystemMessageData(currentPage, 1);

			}
			break;
		default:
			break;
		}
		return false;

	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void finish() {
		super.finish();

		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}

	private void initContentView() {
		initviewPager();
		initMessage();
		initDetailListView();
	}

	private void initDetailListView() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		timetagListView = (ListView) findViewById(R.id.timetag_list);
		detail_layout = (RelativeLayout) findViewById(R.id.detail_relativelayout);
		viewpage_layout = (LinearLayout) findViewById(R.id.viewpage_linearlayout);
		detail_layout.animate().translationX(screenWidth).setDuration(20);
		send_msg_bottom_layout = findViewById(R.id.send_msg_bottom_layout);
		send_msg_bottom_layout.animate().translationX(screenWidth)
				.setDuration(20);
		message_edit = (EditText) (findViewById(R.id.message_content));
		message_send_btn = (ImageButton) (findViewById(R.id.message_send_btn));
		message_send_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (privateMessage.size() > currentMessageDetail) {
					PrivateMessage message = privateMessage
							.get(currentMessageDetail);
					int toUserId = message.getToUserId();
					if (mSharePreferencesManager.readUserId() == toUserId) {
						toUserId = message.getFromUserId();
					}
					mLocalDataLoader.startInsertOneMessageData(toUserId,
							message_edit.getText().toString(),
							new InsertUserMessageLishenter() {

								@Override
								public void requestInsertUserMessageResult(
										int code) {
									switch (code) {
									case LocalDataLoaderHelp.SEND_MESSAGE_SUCCESS_DONE_ACTION:
										PrivateMessage message = new PrivateMessage();
										message.setFromUserId(mSharePreferencesManager
												.readUserId());
										message.setContent(message_edit
												.getText().toString());
										message.setSender(mSharePreferencesManager
												.readUserName());
										if (clockAdapter != null) {
											clockAdapter
													.addPrivateMessage(message);
											clockAdapter.notifyDataSetChanged();
										}
										timetagListView.setSelection(clockAdapter.getCount());
										message_edit.setText(null);
										break;
									case LocalDataLoaderHelp.SEND_MESSAGE_ERROR_DONE_ACTION:
										break;
									default:
										break;
									}
								}
							});
				}
			}
		});
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& detail_layout.getVisibility() == View.VISIBLE) {
			viewpage_layout.animate().translationX(0).setDuration(300);
			detail_layout.animate().translationX(screenWidth).setDuration(300);
			detail_layout.setVisibility(View.GONE);
			send_msg_bottom_layout.animate().translationX(screenWidth)
					.setDuration(300);
			send_msg_bottom_layout.setVisibility(View.GONE);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initPrivateMessageData(int index, final int doType) {
		mLocalDataLoader.startLoadAllMessageData(index,
				new MessageRequestLishenter() {

					@Override
					public void requestMessageList(
							List<PrivateMessage> messages, Page page) {
						privateMessage.clear();
						privateMessage.addAll(messages);
						if (adapters != null && adapters.size() > currentTab) {
							adapters.get(currentTab).notifyDataSetChanged();
						}
						initNoMessageVisible(currentTab);
						handler.sendMessage(handler.obtainMessage(doType, 0, 0));
					}
				});
	}

	private void initSystemMessageData(int index, final int doType) {
		mLocalDataLoader.startLoadAllMessageData(index,
				new MessageRequestLishenter() {

					@Override
					public void requestMessageList(
							List<PrivateMessage> messages, Page page) {
						systemMessage.clear();
						systemMessage.addAll(messages);
						if (adapters != null && adapters.size() > currentTab) {
							adapters.get(currentTab).notifyDataSetChanged();
						}
						initNoMessageVisible(currentTab);
						handler.sendMessage(handler.obtainMessage(doType, 0, 0));
					}
				});
	}

	private void initMessage() {
		initPrivateMessageData(1, 0);
		// initPrivateMessage();
		// initSystemMessage();
	}

	private void initviewPager() {
		views = new ArrayList<View>();
		adapters = new ArrayList<MessageAdapter>();
		viewPager = (ViewPager) findViewById(R.id.vPager);

		for (int i = 0; i < 2; i++) {
			DynamicListView dynamicListView = new DynamicListView(context);
			MessageAdapter messageAdapter = new MessageAdapter();
			if (i == 0) {
				initPrivateMessageListView(dynamicListView, messageAdapter);
			} else {
				initSystemMessageListView(dynamicListView, messageAdapter);
			}

			adapters.add(messageAdapter);
			views.add(dynamicListView);
		}

		viewPager.setAdapter(new ViewPagerAdapter(views));
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					msgSwitch.setBackgroundResource(R.drawable.msg_l);
					systemMsg.setTextColor(0xff888888);
					privateMsg.setTextColor(0xff2ba47b);
					break;
				case 1:
					msgSwitch.setBackgroundResource(R.drawable.msg_r);
					systemMsg.setTextColor(0xff2ba47b);
					privateMsg.setTextColor(0xff888888);
					break;
				default:
					break;
				}
				currentTab = arg0;
				initNoMessageVisible(currentTab);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	private void initSystemMessageListView(DynamicListView dynamicListView,
			MessageAdapter messageAdapter) {
		messageAdapter.setMessages(systemMessage);
		dynamicListView.setAdapter(messageAdapter);
		// dynamicListView.setDoMoreWhenBottom(false);
		// dynamicListView.setOnRefreshListener(this);
		// dynamicListView.setOnMoreListener(this);
	}

	private void initPrivateMessageListView(DynamicListView dynamicListView,
			MessageAdapter messageAdapter) {
		messageAdapter.setMessages(privateMessage);
		dynamicListView.setAdapter(messageAdapter);
		dynamicListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				showTimerPicker(position);
			}
		});
		dynamicListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						showItemLongAlertDialog(position);
						return true;
					}

				});
		// dynamicListView.setDoMoreWhenBottom(false);
		// dynamicListView.setOnRefreshListener(this);
		// dynamicListView.setOnMoreListener(this);
	}

	private void showTimerPicker(int position) {
		if (privateMessage.size() > position - 1) {
			currentMessageDetail = position - 1;
			PrivateMessage message = privateMessage.get(position - 1);
			int toUserId = message.getToUserId();
			if (mSharePreferencesManager.readUserId() == toUserId) {
				toUserId = message.getFromUserId();
			}
			mLocalDataLoader.startLoadUserToUserMessageData(toUserId, 1,
					new MessageRequestLishenter() {

						@Override
						public void requestMessageList(
								List<PrivateMessage> messages, Page page) {
							clockAdapter = new ClockAdapter(
									MyMessageActivity.this, messages,
									mSharePreferencesManager.readUserId());
							timetagListView.setAdapter(clockAdapter);

							viewpage_layout.animate()
									.translationX(-screenWidth)
									.setDuration(300);
							detail_layout.setVisibility(View.VISIBLE);
							detail_layout.animate().translationX(0)
									.setDuration(300);
							send_msg_bottom_layout.setVisibility(View.VISIBLE);
							send_msg_bottom_layout.animate().translationX(0)
									.setDuration(300);
						}
					});
		}
	}

	private void showItemLongAlertDialog(final int position) {
		final PrivateMessage message = privateMessage.get(position - 1);
		Builder builder = new Builder(MyMessageActivity.this);
		builder.setIcon(R.drawable.message_delete_icon);
		builder.setTitle(getResources().getString(R.string.alertdialog_title));
		String msg = String.format(
				getResources().getString(R.string.delete_message_content),
				message.getReceiver());
		builder.setMessage(msg);
		builder.setPositiveButton(
				getResources().getString(R.string.alertdialog_ok),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						int toUserId = message.getToUserId();
						if (mSharePreferencesManager.readUserId() == toUserId) {
							toUserId = message.getFromUserId();
						}
						mLocalDataLoader.startDeleteUserToUserMessageData(
								toUserId, new DeleteUserMessagesLishenter() {

									@Override
									public void requestDeleteUserMessageResult(
											int code) {
										switch (code) {
										case LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION:
											privateMessage.remove(position - 1);
											if (adapters != null) {
												adapters.get(currentTab)
														.notifyDataSetChanged();
											}
											break;
										case LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION:
											break;
										default:
											break;
										}
									}
								});
					}
				});
		builder.setNegativeButton(
				getResources().getString(R.string.alertdialog_cancel),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.setCanceledOnTouchOutside(false);
		// Window w = alertDialog.getWindow();
		// w.setGravity(Gravity.BOTTOM);
		// alertDialog.setCancelable(false);
		alertDialog.show();
	}

	private void initNoMessageVisible(int page) {
		switch (page) {
		case 0:
			if (privateMessage != null && privateMessage.size() != 0) {
				noMessage.setVisibility(View.GONE);
			} else {
				noMessage.setVisibility(View.VISIBLE);
			}
			break;
		case 1:
			if (systemMessage != null && systemMessage.size() != 0) {
				noMessage.setVisibility(View.GONE);
			} else {
				noMessage.setVisibility(View.VISIBLE);
			}
			break;
		default:
			break;
		}
	}

	public class MessageAdapter extends BaseAdapter {
		private List<PrivateMessage> message;

		public MessageAdapter() {
		}

		public MessageAdapter(List<PrivateMessage> message) {
			this.message = message;
		}

		public void setMessages(List<PrivateMessage> message) {
			this.message = message;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			ViewGroup root = null;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.message_item, root);
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.content = (TextView) convertView
						.findViewById(R.id.content);
				holder.head = (ImageView) convertView.findViewById(R.id.head);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.content.setText(message.get(position).getContent());
			MessageIconDrawable messageIcon = new MessageIconDrawable(
					MyMessageActivity.this.getResources());
			messageIcon.setIsCircular(true);
			int toUserId = message.get(position).getToUserId();
			if (mSharePreferencesManager.readUserId() == toUserId) {
				messageIcon.setContactDetails(
						message.get(position).getSender(), message
								.get(position).getContent());
				holder.name.setText(message.get(position).getSender());
			} else {
				messageIcon.setContactDetails(message.get(position)
						.getReceiver(), message.get(position).getContent());
				holder.name.setText(message.get(position).getReceiver());
			}
			holder.head.setImageDrawable(messageIcon);

			return convertView;
		}

		public final int getCount() {
			return message.size();
		}

		public final Object getItem(int position) {
			return message.get(position);
		}

		public final long getItemId(int position) {
			return position;
		}

	}

	public class ViewHolder {
		private TextView name;
		private TextView content;
		private ImageView head;
	}

	public class ViewPagerAdapter extends PagerAdapter {
		private List<View> mListViews;

		public ViewPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(mListViews.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mListViews.get(position), 0);
			return mListViews.get(position);
		}

	}
}
